<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of TaskController
 *
 * @author QuangKhoi
 */
class TaskController {

    /**
     * Store model object
     * @var Task
     */
    private $model;

    /**
     * Store view for the stream
     * @var TaskView
     */
    private $view;

    /**
     * 
     * @param type $model
     * @param type $view
     */
    public function __construct($model, $view) {
        $this->model = $model;
        $this->view = $view;
    }

    public function render() {
        //Need to edit
        //Param parser
        #remove the directory path we don't want 
        $url = $_SERVER['REQUEST_URI'];
        $request = ltrim($url, '/');
        if (strpos($request, '?') != '') {
            $request = substr($request, 0, strpos($request, "?"));
        }
        #split the path by '/'
        $params = split("/", $request);
        $error = '';
        $signals = array();
        if ($params[2] == '') {
            $params[2] = $params[1];
            $params[1] = 'Tasks';
        }
        if (strtoupper($params[2]) != 'VIEWPORT') {
            $db = Database::getInstance();
            $taskIds = array();
            $user = User::getLogedInUser();
            $userId = $user->id;
            if (strtoupper($params[1]) == 'TASKS') {
                $result = $db->Query("SELECT * FROM tasks WHERE (taskuserid = '$userId' OR taskassignedto = '$userId') AND tasktype < 10  ORDER BY taskdatecreated DESC");
                if ($result->returnCode == 200) {
                    if ($result->dataTable->numOfRow > 0) {
                        $rows = $result->dataTable->rows;
                        foreach ($rows as $row) {
                            $taskIds[] = $row["taskid"];
                        }
                    }
                }
            } else if (strtoupper($params[1]) == 'MANAGER') {
                $typeLimit = "";
                $type = strtoupper($_REQUEST['filter']);
                switch($type) {
                    case "TASKS":
                        $typeLimit = "AND tasktype < 10";
                        break;
                    case "EMAIL":
                        $typeLimit = "AND tasktype = 10";
                        break;
                    case "SMS";
                        $typeLimit = "AND tasktype = 11";
                        break;
                }
                if ($user->managerId == 0)
                    $query = "SELECT * FROM tasks WHERE (taskuserid IN (SELECT userid FROM users WHERE teamid = $user->teamId) OR taskassignedto IN (SELECT userid FROM users WHERE teamid = $user->teamId)) $typeLimit ORDER BY taskdatecreated DESC";
                else
                    $query = "SELECT * FROM tasks WHERE (taskuserid = $user->id OR taskassignedto = $user->id) $typeLimit ORDER BY taskdatecreated DESC";
                
                $result = $db->Query($query);
                
                if ($result->returnCode == 200) {
                    if ($result->dataTable->numOfRow > 0) {
                        $rows = $result->dataTable->rows;
                        foreach ($rows as $row) {
                            $taskIds[] = $row["taskid"];
                        }
                    }
                }
            }
            $tasks = Task::loadTask($taskIds);
        }
        $this->view->model = $this->model;
        $this->view->tasks = $tasks;
        $masterView = MasterView::getInstance();
        $masterView->taskView = $this->view;
        $masterView->params = $params;
    }

    public function save() {
        $model = $this->model;
        if ($model->taskId == '') {
            $dateCreated = $model->taskDateCreated->format("Y-m-d H:i:s");
            $model->taskId = Database::getID("Tasks", "taskid");
            $taskAction = str_replace('\'', "\\'", $model->action);
            $taskPost = str_replace('\'', "\\'", $model->post);
            $taskName = str_replace('\'', "\\'", $model->taskName);
            $query = "INSERT INTO tasks 
                                    (taskname, taskcontent, taskuserid, taskassignedto, 
                                    tasktype, signalid, status, taskdatecreated, action, department, post) VALUES
                                    ('$taskName', '$model->taskNote',
                                    '$model->taskUserId', '$model->taskAssignedTo',
                                    '$model->taskType', '$model->signalId', 
                                    '$model->status', '$dateCreated', '$taskAction', '$model->department', '$taskPost')";
            Database::getInstance()->query($query);
            return $model;
        } else {
            $dateCreated = $model->taskDateCreated->format("Y-m-d H:i:s");
            $query = "UPDATE tasks SET status = '$model->status', action = '$model->action' WHERE taskid = '$model->taskId'";
            Database::getInstance()->query($query);
            return $model;
        }
        return null;
    }

    public function markComplete() {
        $this->model->status = 2;
        return $this->save();
    }

    public function undoComplete() {
        $this->model->status = 1;
        return $this->save();
    }

    public function delete() {
        $taskId = $this->model->taskId;
        $result = Database::getInstance()->query("DELETE FROM tasks WHERE taskid='$taskId'");
        if ($result->returnCode == 200)
            return true;
        return false;
    }
    
    public function addTag($tagId) {
        $tag = Tag::withId($tagId);
        $model = $this->model;
        $result = Database::getInstance()->query("INSERT INTO tagsdata (userid, tagid, taskid, signalid) VALUES ('$model->taskUserId', '$tagId', '$model->taskId', '$model->signalId')");
        if($result->returnCode == 200){
            return $tag->tagName;
        }
        return "failed";
    }
    
    public function removeTag($tagId) {
        $tag = Tag::withId($tagId);
        $model =  $this->model;
        $result = Database::getInstance()->query("DELETE FROM tagsdata WHERE taskid='$model->taskId' AND tagid='$tagId'");
        if($result->returnCode == 200){
            return $tag->tagName;
        }
        return "failed";
    }

}

?>
